import { defineStore } from 'pinia'
import { storage } from '@/utils/storage';
import { ref } from 'vue';
import { user_permissions } from '@/api/index'
// import { useRouter } from 'vue-router';
// const router = useRouter()
import router from '@/router/index'
import DynamicRoutes from '@/router/mainRoutes'
// import {Route, MyStoreState} from '@/type/data'
import { recursionRouter, setDefaultRoute, allRouter} from "@/utils/recursion-router"
import dynamicRouter from '@/router/dynamic-router'
import { Route as Route2 } from "@/router/index";

interface Route {
  name: string,
  children?: Array<Route>
}
interface MyStoreState {
  permissionList: Route[],
  sidebarMenu: Route[],
  currentMenu: string,
}
interface ChildRoute {
  path: string;
  name: string;
  component: any;
  meta: RouteMeta;
  children: ChildRoute[]
}
interface RouteMeta {
  name: string;
  icon: string;
}

export const userInfoStore = defineStore('permission', () => {
  const permissionList = ref<any>(null) // 所有路由
  const sidebarMenu = ref<Route[]>([]) // 导航菜单
  const currentMenu = ref() // 高亮
  const isSidebarNavCollapse = ref() // 折叠
  const token = ref<string>(storage.get('token') || '')
  // 设置权限
  const SET_PERMISSION = (routes:Array<any>) => {
    permissionList.value = routes
  }
  // 清除权限
  const CLEAR_PERMSSION = () => {
    permissionList.value = []
  }
  // 设置菜单
  const SET_MENU = (menu: Route[]) => {
    sidebarMenu.value = menu
    // console.log('sidebarMenu.value',sidebarMenu.value)
  }
  // 清除菜单
  const CLEAR_MENU = () => {
    sidebarMenu.value = []
  }

  const setToken = (key: string, data: any) => {
    token.value = data
    storage.set(key, data)
  }

  // 获取权限列表
  const FETCH_PERMISSION = async () => {
    let id = null
    if (token.value == 'admin') {
      id = 1
    } else {
      id = 2
    }
    let permissionList = await user_permissions(id)
    let routes = recursionRouter(permissionList.data.attributes.data.data, dynamicRouter);
    let MainContainer:any = DynamicRoutes.find(v =>  v.path == "");
    // console.log('MainContainer',MainContainer)
    let children:any= MainContainer.children
    children.push(...routes)
    console.log('children',children)

    SET_MENU(children);

    // 设置默认路由
    setDefaultRoute([MainContainer]);

    // 初始化路由
    let initialRoutes = router.options.routes;
    console.log('router',router)
    console.log('initialRoutes',initialRoutes)
    console.log([...initialRoutes, ...DynamicRoutes])
    // router.addRoute(DynamicRoutes)
    SET_PERMISSION([...initialRoutes, ...DynamicRoutes])
  }


  return { permissionList, sidebarMenu, currentMenu,isSidebarNavCollapse, token, SET_PERMISSION, CLEAR_PERMSSION, SET_MENU, CLEAR_MENU, setToken, FETCH_PERMISSION }
})